﻿using Entity;
using IService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.Extensions.Logging; // 引入日志命名空间

namespace XingWeiDaWMSProject.Controllers
{
    public class GoodsTypeController : Controller
    {
        private readonly ITypeOfGoodsService _typeOfGoodsService;
        private readonly ILogger<GoodsTypeController> _logger; // 日志对象

        public GoodsTypeController(ITypeOfGoodsService typeOfGoodsService, ILogger<GoodsTypeController> logger)
        {
            _typeOfGoodsService = typeOfGoodsService;
            _logger = logger;
        }
        public IActionResult Index()
        {
            if (Request.Headers["X-Requested-With"] == "XMLHttpRequest")
            {
                // AJAX请求：返回部分视图（无布局）
                return PartialView();
            }
            else
            {
                // 普通请求：返回完整视图（带布局）
                return View();
            }
        }

        [HttpGet]
        public async Task<IActionResult> GetGoodsTypeTree(string goodsType = null, string status = null, string @operator = null, DateTime? startTime = null, DateTime? endTime = null)
        {
            var treeData = await _typeOfGoodsService.GetGoodsTypeTreeAsync(goodsType, status, @operator, startTime, endTime);
            _logger.LogInformation($"根节点数量：{treeData.Count}");
            if (treeData.Any())
            {
                _logger.LogInformation($"第一个根节点的子节点数量：{treeData[0].Children.Count}");
            }
            return Json(treeData);
        }


        [HttpGet]
        public async Task<IActionResult> GetParentTypeOptions()
        {
            try
            {
                // 调用Service层已实现的方法，获取带层级的选项列表
                var options = await _typeOfGoodsService.GetParentTypeOptionsAsync();
                // 在选项列表最前面添加“无上级分类”选项
                options.Insert(0, new WMSBasicTypeOfGoods
                {
                    product_type_id = 0,
                    product_type_name = "无上级分类",
                    product_type_code = ""
                });
                return Json(options);
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "获取上级分类选项失败");
                return Json(new { success = false, message = "获取上级分类失败" });
            }
        }


        [HttpPost]
        public async Task<IActionResult> AddTypes([FromBody] AddWMSBasicTypeOfGoods model)
        {
            try
            {
                if (model == null)
                {
                    return Json(new { success = false, message = "请求数据格式错误" });
                }

                if (string.IsNullOrEmpty(model.product_type_name))
                {
                    return Json(new { success = false, message = "货品类型名称不能为空" });
                }
                model.create_by = User.Identity?.Name ?? "admin";
                model.create_time = DateTime.Now; // 可空类型可以直接赋值

                await _typeOfGoodsService.AddTypesAsync(model);

                return Json(new { success = true, message = "添加成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "添加货品类型失败");
                return Json(new { success = false, message = $"服务器错误:{ex.Message}" });
            }
        }


        [HttpGet]
        public async Task<IActionResult> GetType(string product_type_code)
        {
            try
            {
                var model = await _typeOfGoodsService.SelectTypeAsync(product_type_code);
                if (model == null)
                {
                    return Json(new { success = false, message = "货品类型不存在" });
                }
                return Json(new { success = true, data = model });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "查询货品类型失败");
                return Json(new { success = false, message = $"服务器错误:{ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> UpdateType([FromBody] AddWMSBasicTypeOfGoods model)
        {
            try
            {
                if (model == null)
                {
                    return Json(new { success = false, message = "请求数据格式错误" });
                }
                if (string.IsNullOrEmpty(model.product_type_name))
                {
                    return Json(new { success = false, message = "货品类型名称不能为空" });
                }
                model.update_by = User.Identity?.Name ?? "admin";
                model.update_time = DateTime.Now;
                await _typeOfGoodsService.UpdateTypesAsync(model);
                return Json(new { success = true, message = "修改成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "修改货品类型失败");
                return Json(new { success = false, message = $"服务器错误:{ex.Message}" });
            }
        }

        [HttpPost]
        public async Task<IActionResult> DeleteType(string product_type_code)
        {
            try
            {
                await _typeOfGoodsService.DeleteTypesAsync(product_type_code);
                return Json(new { success = true, message = "删除成功" });
            }
            catch (Exception ex)
            {
                _logger.LogError(ex, "删除货品类型失败");
                return Json(new { success = false, message = $"服务器错误:{ex.Message}" });
            }
        }


    }
}
